<template>
  <!--  面包屑导航-->
  <div class="break">
    <el-breadcrumb separator=">">
      <el-breadcrumb-item>首页</el-breadcrumb-item>
      <el-breadcrumb-item>人事管理</el-breadcrumb-item>
      <el-breadcrumb-item>出勤管理</el-breadcrumb-item>
      <el-breadcrumb-item><b>出警申请</b></el-breadcrumb-item>
    </el-breadcrumb>
  </div>
  <!-- 搜索工具栏-->
  <div style="margin:40px 20px 20px 20px">
    <el-form :inline="true" ref="searchFormRef" :model="searchFormModel" class="demo-form-inline" style="margin-top: 20px">
      <el-form-item label="姓名" prop="applicants">
        <el-input v-model="searchFormModel.applicants" placeholder="请输入姓名" clearable />
      </el-form-item>
      <el-form-item label="部门" prop="department" style="width: 250px">
        <el-select v-model="searchFormModel.department" placeholder="请选择部门" clearable>
          <el-option label="财务部" value="财务部"/>
          <el-option label="后勤部" value="后勤部"/>
          <el-option label="人力部" value="人力部"/>
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status" style="width: 250px">
        <el-select v-model="searchFormModel.status" placeholder="请输入状态" clearable >
          <el-option label="待审核" value="待审核"/>
          <el-option label="已通过" value="已通过"/>
          <el-option label="已驳回" value="已驳回"/>
          <el-option label="已撤销" value="已撤销"/>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="success" @click="searchOnSubmit">查询</el-button>
        <el-button style="background-color: pink" @click="dialogAddState=true">添加</el-button>
      </el-form-item>
    </el-form>
  </div>

  <!--  数据表格-->
  <div style="margin:20px">
    <el-table :data="blogInfo" stripe border style="width: 100%"
    >
      <el-table-column prop="applicants" label="申请人" />
      <el-table-column prop="dispatch_date" label="出警日期"  />
      <el-table-column prop="dispatch_time" label="出警时间"  />
      <el-table-column prop="department" label="部门"  />
      <el-table-column prop="dispatch_content" label="理由"  />
      <el-table-column prop="dispatch_place" label="地点"  />
      <el-table-column prop="status" label="状态">
        <template #default="scope">
          <el-tag :type="statusType(scope.row.status)">
            {{ scope.row.status }}
            <span v-if="scope.row.status === '待审核'" class="status-indicator status-s"></span>
            <span v-if="scope.row.status === '已通过'" class="status-indicator status-t"></span>
            <span v-if="scope.row.status === '已驳回'" class="status-indicator status-b"></span>
            <span v-if="scope.row.status === '已撤销'" class="status-indicator status-c"></span>
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="160">
        <template #default="scope">
          <el-button
              size="small"
              :disabled="scope.row.status === '' || scope.row.status === '待审核' || scope.row.status === '已通过'"
              @click="tableEditHandler(scope.$index, scope.row)">
            <el-icon><Edit /></el-icon>编辑
          </el-button>
          <el-button
              size="small"
              type="danger"
              :disabled="scope.row.status === '已撤销' || scope.row.status === '已驳回' || scope.row.status === '已通过'"
              @click="tableDeleteHandler(scope.row.id)">
            <el-icon><Switch /></el-icon>撤销
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>

  <!--  分页-->
  <div class="page">
    <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[3,5]"
        :small="small"
        :disabled="disabled"
        :background="background"
        layout="sizes, prev, pager, next"
        :total="totals"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    />
  </div>

  <!-- 添加模态框 -->
  <el-dialog v-model="dialogAddState" title="添加出警申请" width="680">
    <div>
      <el-form ref="formAddRef" :model="formAdd" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item prop="applicants" label="申请人">
              <el-input v-model="formAdd.applicants"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="department" label="部门">
              <el-select v-model="formAdd.department" placeholder="请选择部门">
                <el-option label="财务部" value="财务部"/>
                <el-option label="后勤部" value="后勤部"/>
                <el-option label="人力部" value="人力部"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item prop="dispatch_date" label="出警日期">
              <el-date-picker
                  v-model="formAdd.dispatch_date"
                  type="date"
                  placeholder="选择日期"
                  @change="formatDate">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="dispatch_time" label="出警时间">
              <el-date-picker
                  v-model="formAdd.dispatch_time"
                  type="datetime"
                  placeholder="选择日期时间"
                  @change="formatDate1"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="dispatch_content" label="原因">
              <el-input v-model="formAdd.dispatch_content"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item prop="dispatch_place" label="出警地点">
              <el-input v-model="formAdd.dispatch_place"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogAddOnReset">取消</el-button>
        <el-button type="primary" @click="submitRegisterForm">确认</el-button>
      </div>
    </template>
  </el-dialog>
  <!--  编辑模态框-->
  <el-dialog v-model="dialogEditState" title="修改申请信息" width="700">
    <div>
      <el-form ref="formEditRef" :model="formEdit" label-width="120px">
        <el-form-item v-if="false" prop="id" label="序号">
          <el-input v-model="formEdit.id"></el-input>
        </el-form-item>
        <el-form-item prop="applicants" label="申请人">
          <el-input v-model="formEdit.applicants" readonly style="background-color: darkgray"></el-input>
        </el-form-item>
        <el-form-item prop="department" label="部门">
          <el-input v-model="formEdit.department" ></el-input>
        </el-form-item>
        <el-form-item prop="dispatch_date" label="出警日期">
          <el-input v-model="formEdit.dispatch_date" ></el-input>
        </el-form-item>
        <el-form-item prop="dispatch_time" label="出警时间">
          <el-input v-model="formEdit.dispatch_time" ></el-input>
        </el-form-item>
        <el-form-item prop="dispatch_content" label="原因">
          <el-input v-model="formEdit.dispatch_content" ></el-input>
        </el-form-item>
        <el-form-item prop="dispatch_place" label="地点">
          <el-input v-model="formEdit.dispatch_place" ></el-input>
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogEditOnReset">取消</el-button>
        <el-button type="primary"  @click="dialogEditOnSubmit" >确认</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import {Unlock,Lock,Delete,Edit,Switch} from "@element-plus/icons";
import {onMounted, reactive, ref} from "vue";
import request from "@/utils/people";
import {ElMessage, ElMessageBox} from "element-plus";
const userInfo = reactive({
  'username' :null
})
onMounted(()=>{
  // 从SessionStorage取出数据
  let userstr = sessionStorage.getItem('loginUser')

  userInfo.username = JSON.parse(userstr).id
  getGopolice();
})

const statusType = (status) => {
  if (status === '已通过') {
    return 'success'; // 绿色
  } else if (status === '待审核') {
    return 'danger'; // 红色
  } else {
    return '';
  }
};
// 表格显示内容
const getGopolice = () => {
  const params = {
    pageNum: currentPage.value,
    pageSize: pageSize.value,
    information_id:userInfo.username
    // 初始时不包含ID参数
  };
  //模糊查询
  if (searchFormModel.applicants && searchFormModel.applicants.trim() !== '') {
    params.applicants = searchFormModel.applicants.trim();
  }
  if (searchFormModel.status && searchFormModel.status.trim() !== '') {
    params.status = searchFormModel.status.trim();
  }
  if (searchFormModel.department && searchFormModel.department.trim() !== '') {
    params.department = searchFormModel.department.trim();
  }
  request({
    url: '/gopolice/getone',
    method: 'get',
    params,
  }).then((req) => {
    console.log(req)
    if (200 == req.data.errorCode) {
      blogInfo.value = req.data.data.records.map(item => ({
        ...item,
      }));
      totals.value = req.data.data.total;
    }
  })
}

//分页
const currentPage = ref(1)
const pageSize = ref(5)
const small = ref(false)
const background = ref(false)
const disabled = ref(false)
let totals=ref(0);
const  blogInfo=ref([])
const handleSizeChange = (val) => {
  console.log(`${val} items per page`)
  pageSize.value=val;
  getGopolice()
}
const handleCurrentChange = (val) => {
  console.log(`current page: ${val}`)
  currentPage.value=val;
  getGopolice()
}
//搜索
const searchFormRef=ref()
const searchFormModel=reactive({
  applicants:'',
  dispatch_date:'',
  dispatch_time:'',
  department:'',
  dispatch_content:'',
  dispatch_place:'',
  status:''
})
const searchOnSubmit=()=>{
  getGopolice()
}



///////////////////添加/////////////////////////
const dialogAddState = ref(false);
const formAddData = {
  id:'',
  information_id:'',
  applicants:'',
  dispatch_date:'',
  dispatch_time:'',
  department:'',
  dispatch_content:'',
  dispatch_place:'',
  status:''
};
const formAdd = reactive({...formAddData});
const addressFormRef = ref(null); // 创建一个ref引用form
// 提交表单
const submitRegisterForm = ()=>{
  formAdd.information_id = userInfo.username;
  request({
    method:'post',
    url:'/gopolice/insert',
    params:formAdd,
    headers:{'content-type' : "application/json;charset=UTF-8"}
  }).then(req=>{
    ElMessage({
      type:'info',
      message:req.data.msg
    })
    if (200 == req.data.errorCode){
      Object.assign(formAdd,formAddData)
      getGopolice()
    }
  })
  dialogAddState.value=false;
}
const dialogAddOnReset = () => {
  Object.assign(formAdd , formAddData)
  dialogAddState.value = false
}
const rules = {
  applicants: [
    { required: true, message: '请输入申请人姓名', trigger: 'blur' },
    { validator: validateChinese, trigger: 'blur' }
  ],
  department: [
    { required: true, message: '请选择部门', trigger: 'change' }
  ],
  dispatch_date: [
    { required: true, message: '请选择出警日期', trigger: 'change' }
  ],
  dispatch_time: [
    { required: true, message: '请选择出警时间', trigger: 'change' }
  ],
  dispatch_content: [
    { required: true, message: '请输入出警原因', trigger: 'blur' }
  ],
  dispatch_place: [
    { required: true, message: '请输入出警地点', trigger: 'blur' }
  ]
};

// 验证申请人姓名是否为中文
function validateChinese(rule, value, callback) {
  const regex = /^[\u4e00-\u9fa5]+$/;
  if (!value) {
    return callback(new Error('请输入申请人姓名'));
  } else if (!regex.test(value)) {
    return callback(new Error('申请人姓名必须为中文'));
  } else {
    return callback();
  }
}
//时间设置//
const formatDate=(value)=> {
  if (!value) {
    // 如果日期时间选择器的值为空，则不进行格式化
    formAdd.dispatch_date = '';
    return;
  }
  // 将日期时间字符串转换为Date对象
  const date = new Date(value);
  // 获取年、月、日、小时、分钟和秒
  const year = date.getFullYear();
  const month = (date.getMonth() + 1).toString().padStart(2, '0');
  const day = date.getDate().toString().padStart(2, '0');

  // 组合成所需的格式
  formAdd.overbegintime = `${year}-${month}-${day} `;
}

const formatDate1=(value)=> {
  if (!value) {
    // 如果日期时间选择器的值为空，则不进行格式化
    formAdd.dispatch_time = '';
    return;
  }
  // 将日期时间字符串转换为Date对象
  const date = new Date(value);
  // 获取年、月、日、小时、分钟和秒
  const year = date.getFullYear();
  const month = (date.getMonth() + 1).toString().padStart(2, '0');
  const day = date.getDate().toString().padStart(2, '0');
  const hours = date.getHours().toString().padStart(2, '0');
  const minutes = date.getMinutes().toString().padStart(2, '0');
  const seconds = date.getSeconds().toString().padStart(2, '0');

  // 组合成所需的格式
  formAdd.dispatch_time = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}
//////////////////编辑///////////////////////
const formEdit = reactive({...formAddData})
const tableEditHandler = (rowIndex , rowData) => {
  console.log("-------------")
  console.log(rowIndex)
  console.log(rowData)

  formEdit.id = rowData.id
  formEdit.applicants= rowData.applicants
  formEdit.department = rowData.department
  formEdit.dispatch_date=rowData.dispatch_date
  formEdit.dispatch_time=rowData.dispatch_time
  formEdit.dispatch_place=rowData.dispatch_place
  formEdit.dispatch_content = rowData.dispatch_content
  dialogEditState.value = true
}
const dialogEditState = ref(false)

const dialogEditOnSubmit = () => {
  request({
    url:'/gopolice/update',
    method:'put',
    data:JSON.stringify(formEdit),
    headers:{'content-type' : "application/json;charset=UTF-8"}
  }).then(req=>{
    ElMessage({
      type:'info',
      message:req.data.msg
    })
    if (200==req.data.errorCode){
      getGopolice();
    }
  })
  dialogEditState.value = false
}
const dialogEditOnReset = () => {
  Object.assign(formEdit , formAddData)
  dialogEditState.value = false
}
//撤销
const tableDeleteHandler = (id) => {
  request({
    url: `/gopolice/updateS?id=${id}`, // 如果后端通过 URL 参数接收 ID
    method: 'put',
    // 如果后端期望 ID 在请求体中，可以这样设置
    data: JSON.stringify({...formEdit, id }),
    headers: {'content-type': "application/json;charset=UTF-8"}
  }).then(req => {
    ElMessage({
      type: 'info',
      message: req.data.msg
    });
    if (200 === req.data.errorCode) {
      getGopolice();
    }
  });
  dialogEditState.value = false;
};
</script>

<style scoped>
.page{
  margin-left: 40%;
}
.el-breadcrumb{
  font-size: 18px;
}
.break{
  margin: 5px 0 0 10px;
}
.status-indicator {
  display: inline-block;
  width: 10px;
  height: 5px;
  border-radius: 50%;
  margin-left: 5px;
  vertical-align: middle;
  position: relative;
  top: -3px;
  background-color: transparent !important; /* 防止el-tag背景色影响 */
}

.status-s {
  background-color: green;
}
.status-b {
  background-color: green;
}

.status-t {
  background-color: red;
}
.status-c {
  background-color: red;
}
</style>